<template>
  <div class='comment'>
         <h4>发表评论</h4>
          <hr>
         <textarea placeholder='请输入要评论的内容（最大120字）' maxlength='120' v-model='msg'></textarea>
         <mt-button type='primary' size='large' @click='postComment'>发表评论</mt-button>
         <ul class='comment-body'>
           <li v-for='(item,i) in list' :key='item.add_time'>
             <div>第{{i+1}}楼&nbsp;&nbsp;用户：{{item.user_name}}&nbsp;&nbsp;发表时间：{{item.add_time | dataFormat}}</div>  
             <p>{{item.content==='undefined'?'此用户很懒，嘛都没说':item.content}}</p>          
           </li>
         </ul>
         <mt-button type='danger' size='large' plain @click='getMoreComts'>加载更多</mt-button>
      </div>
</template>
<script>
import {Toast} from 'mint-ui';
    export default{
      data(){
        return {
          list:[],
          pageindex:1,
          msg:''
        }
      },
      created(){
        this.getComments()
      },
      methods:{
        getComments(){
          this.$http.get('api/getcomments/'+this.id+'?pageindex='+this.pageindex).then(results=>{
            console.log(results.body,this.id)
            if(results.body.status==0){
              this.list=this.list.concat(results.body.message);
            }else{
              Toast('err!');
            }
          })
        },
        getMoreComts(){
          this.pageindex++;
          this.getComments();
        },
        postComment(){
          // 判断是否为空内容
         if(this.msg.trim().length==0) return Toast('输入内容不能为空！')
         
          this.$http.post('api/postcomment/'+this.id,{content:this.msg}).then((results=>{
            console.log(results.body);
            if(results.body.status===0){
              // 手动创建一个对象，追加到list数组的最前面，这样避免pageindex值等于大于1的值时不渲染第一页的情况
              var comt={user_name:'匿名用户',add_time:Date.now(),content:this.msg.trim()};
              this.list.unshift(comt);
              this.msg='';
            }else{
              Toast('评论失败！');
            }
          }))
        }
      },
        props:["id"]

    }

</script>
<style scoped lang='scss'>
.comment{
  textarea{
font-size:12px;
margin:0;
  }
  ul{
    padding:0;
    margin:7px 0;
    li{
      list-style:none;
      div{
        background-color:#ccc;
        line-height: 30px;
        font-size:12px;
      }
      p{
        text-indent:2em;
        line-height: 30px;
      }
    }
  }
}
</style>

